const debounce = (func, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = null
    timer = setTimeout(() => {
      func.apply(self, args)
    }, delay)
  }
}
export default {
  mounted(el, binding) {
    /**
     * target 目标DOM节点的类名
     * distance 减少触发加载的距离阈值，单位为px
     * func 触发的方法
     * delay 防抖时延，单位为ms
     */
    let { target, distance = 0, func, delay = 200 } = binding.value
    if (!target && typeof target !== 'string') return
    let dom = el.querySelector(target)
    binding.scroll = debounce(() => {
      const { scrollTop, scrollHeight, clientHeight } = dom
      if (scrollHeight <= scrollTop + clientHeight + distance) {
        func && func()
      }
    }, delay)
    dom.addEventListener('scroll', binding.scroll)
  },
  unmounted(el, binding) {
    const { target } = binding.value
    let dom = el.querySelector(target)
    dom.removeEventListener('scroll', binding.scroll)
  },
}
